import axios from 'axios'
import xyMessage from '@/components/xyMessage/xyMessage'
// 创建 axios 实例
const request = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 开发环境下设置baseURL为空，让mockjs拦截请求
    if (process.env.NODE_ENV === 'development') {
      config.baseURL = ''
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    if (response.data.code == 200) {
      return response.data?.data
    } else {
      xyMessage.error('错误信息:' + response.data?.message)
      return Promise.reject(response.data?.message)
    }
  },
  error => {
    console.error('API请求错误:', error)
    xyMessage.error('API请求错误:' + error)
    return Promise.reject(error)
  }
)

export default request
